package petstore.web.servlet.cart;

import petstore.persistence.CartDaoImpl;
import petstore.persistence.impl.CartDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/addItemToCart")
public class AddItemToCartServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        req.setCharacterEncoding("UTF-8");
        String itemId = req.getParameter("itemId");
        HttpSession session = req.getSession();
        if(session.getAttribute("uid") == null)
        {
            System.out.println("add null");
            resp.setCharacterEncoding("UTF-8");
            resp.setHeader("content-type","text/html,charset=utf-8");
            resp.setHeader("refresh","0.1;URL=login");
            resp.getWriter().write("<script language='javascript'>alert('\\u8bf7\\u5148\\u767b\\u5f55')</script>");
            return;
        }
        CartDaoImpl cartDao = new CartDaoImpl((int)session.getAttribute("uid"));
        cartDao.addItem(itemId,1);
        //resp.setHeader("Refresh","0;url = \"/WEB-INF/jsp/cartPage/cartPage.jsp\"");
        resp.sendRedirect("cart");
    }
}
